package com.nirvana.ui;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;


/**
 * Copyright (c) 2022 Aoshu.Co.Ltd. All rights reserved.
 *
 * @author :    zhouqichun
 * @create :    2024/8/16 11:49
 * @description : 支持搜索过滤文件
 **/

public class SearchFileChooser extends JFileChooser {
    private JTextField filterTextField;

    public SearchFileChooser() {
        super();
        setMinimumSize(new Dimension(500, 300));
        setPreferredSize(new Dimension(1000, 600));
        setMaximumSize(new Dimension(1500, 900));
        initTextField();
    }

    private void initTextField() {

        JPanel panel = new JPanel(new BorderLayout());
        filterTextField = new JTextField(35) {
            public Dimension getMaximumSize() {
                return new Dimension(Short.MAX_VALUE, super.getPreferredSize().height);
            }
        };
        filterTextField.getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                filterFiles();
            }

            public void removeUpdate(DocumentEvent e) {
                filterFiles();
            }

            public void changedUpdate(DocumentEvent e) {
                filterFiles();
            }
        });
        panel.add(new JLabel("过滤文件名："), BorderLayout.WEST);
        panel.add(filterTextField);
        ((JPanel) getComponent(2)).add(panel, BorderLayout.SOUTH);
    }

    protected void filterFiles() {
        String text = filterTextField.getText();
        removeChoosableFileFilter(getFileFilter());
        setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if (f != null) {
                    if (f.isDirectory()) {
                        return true;
                    }
                    String fileName = f.getName();
                    return fileName.contains(text);
                }
                return false;
            }

            @Override
            public String getDescription() {
                return "搜索过滤";
            }
        });
        rescanCurrentDirectory();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SearchFileChooser fileChooser = new SearchFileChooser();
                int result = fileChooser.showOpenDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    System.out.println("Selected file: " + file.getAbsolutePath());
                }
            }
        });
    }
}
